<template>
  <div class="user-manage">
    <div style="display: flex;">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-4">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="queryForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="queryForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryForm.roleId" placeholder="全部角色" clearable>
            <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="全部状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <div class="operation-buttons mb-4">
          <el-button type="primary" icon="el-icon-download" @click="handleExport">导出用户列表</el-button>
        </div>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table :data="tableData" border stripe style="width: 100%" header-cell-class-name="table-header">
      <el-table-column prop="id" label="用户ID" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="140" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="roleName" label="角色" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.roleCode)" size="medium">
            {{ scope.row.roleName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="medium">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" fixed="right" width="220" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="editUser(scope.row)">
            编辑
          </el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'warning' : 'success'" 
            size="small" 
            :icon="scope.row.status === 1 ? 'el-icon-lock' : 'el-icon-unlock'"
            @click="toggleUserStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button 
            type="info" 
            size="small" 
            icon="el-icon-refresh-right"
            @click="resetPassword(scope.row.id)"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryForm.pageNum"
      :page-sizes="[10, 20, 50]"
      :page-size="queryForm.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <!-- 编辑弹窗 -->
    <el-dialog 
      :visible.sync="dialogVisible" 
      title="编辑用户信息" 
      width="540px" 
      :close-on-click-modal="false"
      @close="dialogVisible = false"
    >
      <el-form :model="form" :rules="rules" ref="editForm" label-width="100px" class="edit-form">
        <el-form-item label="用户名">
          <el-input v-model="form.username" disabled>
            <i slot="prefix" class="el-input__icon el-icon-user"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名">
            <i slot="prefix" class="el-input__icon el-icon-user-solid"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11">
            <i slot="prefix" class="el-input__icon el-icon-phone"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id">
              <span style="float: left">{{ role.roleName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ role.roleCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">
              <i class="el-icon-circle-check" style="color: #67C23A;"></i> 正常
            </el-radio>
            <el-radio :label="0">
              <i class="el-icon-circle-close" style="color: #F56C6C;"></i> 禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" icon="el-icon-close">取消</el-button>
          <el-button type="primary" @click="saveForm" icon="el-icon-check">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加弹窗 -->
    <!-- 已移除新增用户功能 -->
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserManage',
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        username: '',
        phone: '',
        realName: '',
        roleId: null,
        status: null
      },
      tableData: [],
      total: 0,
      roleList: [],
      dialogVisible: false,
      form: {},
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.fetchRoleList()
    this.fetchUserList()
  },
  methods: {
    handleFilter() {
      this.queryForm.pageNum = 1
      this.fetchUserList()
    },
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        username: '',
        phone: '',
        realName: '',
        roleId: null,
        status: null
      }
      this.fetchUserList()
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchUserList()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.fetchUserList()
    },
    getRoleTagType(roleCode) {
      const typeMap = {
        'ADMIN': 'danger',
        'OPERATOR': 'warning',
        'USER': 'success'
      }
      return typeMap[roleCode] || 'info'
    },
    async fetchRoleList() {
      try {
        const response = await request({
          url: '/role',
          method: 'get'
        })
        if (response.code === 200) {
          this.roleList = response.data || []
        }
      } catch (error) {
        console.error(error)
      }
    },
    async fetchUserList() {
      const loading = this.$loading({ lock: true, text: '加载中...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: '/user/admin',
          method: 'get',
          params: this.queryForm
        })
        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    },
    editUser(row) {
      this.form = { ...row }
      this.dialogVisible = true
    },
    async saveForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return

        const loading = this.$loading({ lock: true, text: '保存中...', spinner: 'el-icon-loading' })
        try {
          const response = await request({
            url: `/user/${this.form.id}`,
            method: 'put',
            data: {
              realName: this.form.realName,
              phone: this.form.phone,
              roleId: this.form.roleId,
              status: this.form.status
            }
          })
          if (response.code === 200) {
            this.$message.success('保存成功')
            this.dialogVisible = false
            this.fetchUserList()
          } else {
            this.$message.error(response.msg || '保存失败')
          }
        } catch (error) {
          this.$message.error(error.response?.data?.msg || '保存失败')
        } finally {
          loading.close()
        }
      })
    },
    async toggleUserStatus(row) {
      const action = row.status === 1 ? '禁用' : '启用'
      try {
        await this.$confirm(`确定要${action}该用户吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const loading = this.$loading({ lock: true, text: `${action}中...`, spinner: 'el-icon-loading' })
        try {
          const response = await request({
            url: `/user/${row.id}/status`,
            method: 'put',
            data: {
              status: row.status === 1 ? 0 : 1
            }
          })
          if (response.code === 200) {
            this.$message.success(`${action}成功`)
            this.fetchUserList()
          } else {
            this.$message.error(response.msg || `${action}失败`)
          }
        } finally {
          loading.close()
        }
      } catch {
        this.$message.info('已取消操作')
      }
    },
    async resetPassword(userId) {
      try {
        await this.$confirm('确定要重置该用户的密码为 123456 吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const loading = this.$loading({ lock: true, text: '重置中...', spinner: 'el-icon-loading' })
        try {
          const response = await request({
            url: `/user/${userId}/password`,
            method: 'put',
            data: {
              password: '123456'
            }
          })
          if (response.code === 200) {
            this.$message.success('密码已重置为 123456')
          } else {
            this.$message.error(response.msg || '重置失败')
          }
        } finally {
          loading.close()
        }
      } catch {
        this.$message.info('已取消操作')
      }
    },
    async deleteUser(userId) {
      // 已移除删除用户功能
    },
    async handleExport() {
      this.$message.info('导出功能开发中...')
      // TODO: 调用导出接口
      // const response = await request({
      //   url: '/user/export',
      //   method: 'get',
      //   params: this.queryForm,
      //   responseType: 'blob'
      // })
    }
  }
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.operation-buttons {
  display: flex;
  justify-content: flex-end;
}

.mb-4 {
  margin-bottom: 16px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格样式优化 */
::v-deep .el-table {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

::v-deep .el-table .table-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

::v-deep .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 表单筛选区域 */
::v-deep .el-form {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 弹窗样式优化 */
::v-deep .el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 8px 8px 0 0;
}

::v-deep .el-dialog__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: white;
  font-size: 20px;
}

::v-deep .el-dialog__body {
  padding: 30px 20px;
}

.edit-form {
  padding: 0 20px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.el-button--success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
  border: none;
}

.el-button--success:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(86, 171, 47, 0.4);
}

.el-button--warning {
  background: linear-gradient(135deg, #f2994a 0%, #f2c94c 100%);
  border: none;
}

.el-button--warning:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(242, 153, 74, 0.4);
}

.el-button--info {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
}

.el-button--info:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

/* 标签样式 */
::v-deep .el-tag {
  border-radius: 12px;
  padding: 0 12px;
  font-weight: 500;
}

/* 输入框图标颜色 */
::v-deep .el-input__icon {
  color: #909399;
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
}
</style>